package com.topboya.officeuser.wx;

import com.alibaba.fastjson.JSONObject;
import com.topboya.officeuser.entity.WxUser;
import com.topboya.officeuser.utils.HttpClientUtils;
import com.topboya.officeuser.utils.Result;
import com.topboya.officeuser.utils.ResultCodeEnum;
import com.topboya.officeuser.utils.UcenterProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.jackson.JsonObjectDeserializer;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.Map;
import java.util.UUID;

/**
 * @className WxLoginController
 * @Author xiaxin
 * @Date 2020/12/18 8:47
 * @Version 1.0
 **/
@RequestMapping("/api/ucenter/wx")
@Controller
public class WxLoginController {


    @Autowired
    UcenterProperties ucenterProperties;

    @RequestMapping("wxLogin")
    public Result reTurn(HttpSession session, HttpServletResponse response){
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";
        String redirectUri = "";
        try {
            redirectUri = URLEncoder.encode(ucenterProperties.getRedirectUri(),"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        String state = UUID.randomUUID().toString();
        System.out.println(state);
        session.setAttribute("wx_open_sate",state);
        String qrcodeUrl = String.format(baseUrl, ucenterProperties.getAppId(), redirectUri, state);

        try {
            response.sendRedirect(qrcodeUrl);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.ok().message(ResultCodeEnum.SUCCESS.toString());
    }

    @ResponseBody
    @RequestMapping("callback")
    public WxUser callback(String code,String state,HttpSession session) throws IOException, ParseException {
        String uri = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";
        String qrcodeUrl = String.format(uri, ucenterProperties.getAppId(), ucenterProperties.getAppSecret(),code);
        HttpClientUtils client = new HttpClientUtils(qrcodeUrl);
        String access_token = null;
        String userInfor = null;
        try {
            client.get();
            String content =client.getContent();
            Map map = (Map) JSONObject.parse(content);

            access_token = (String) map.get("access_token");

            System.out.println("content:"+content);
            System.out.println("token:"+access_token);

        } catch (Exception e) {
            e.printStackTrace();
        }

        String sts = "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=OPENID";
        String qrcls = String.format(sts, access_token);

        HttpClientUtils clientUser = new HttpClientUtils(qrcls);
        clientUser.get();
        userInfor = clientUser.getContent();

        JSONObject user = JSONObject.parseObject(userInfor);
        String openid = (String) user.get("openid");

        String nickname = (String) user.get("nickname");

        String avatar = (String) user.get("headimgurl");

        WxUser wxUser = new WxUser();
        System.out.println(userInfor);

        wxUser.setAvatar(avatar);
        wxUser.setNickName(nickname);
        wxUser.setOpenId(openid);

        System.out.println("code:"+code);
        return wxUser;
    }
}
